package com.example.myapplication;

import android.content.ContentValues;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AddProductActivity extends AppCompatActivity {

    private EditText etName, etDescription, etPrice;
    private ImageView ivProductImage;
    private Button btnAddProduct;
    private DBHelper dbHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_product);

        // 初始化组件
        etName = findViewById(R.id.etName);
        etDescription = findViewById(R.id.etDescription);
        etPrice = findViewById(R.id.etPrice);
        ivProductImage = findViewById(R.id.ivProductImage);
        btnAddProduct = findViewById(R.id.btnAddProduct);

        dbHelper = new DBHelper(this);

        // 添加商品按钮点击事件
        btnAddProduct.setOnClickListener(v -> {
            String name = etName.getText().toString().trim();
            String description = etDescription.getText().toString().trim();
            String priceStr = etPrice.getText().toString().trim();

            if (name.isEmpty() || description.isEmpty() || priceStr.isEmpty()) {
                Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                return;
            }

            double price = Double.parseDouble(priceStr);

            ContentValues values = new ContentValues();
            values.put("name", name);
            values.put("description", description);
            values.put("price", price);
            values.put("image_path", "drawable/book1"); // 示例图片路径

            long result = dbHelper.getWritableDatabase().insert("products", null, values);

            if (result != -1) {
                Toast.makeText(this, "商品发布成功", Toast.LENGTH_SHORT).show();
                finish(); // 返回上一页
            } else {
                Toast.makeText(this, "发布失败，请重试", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
